<?php

namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;

class Post extends Model
{
    use Searchable, SoftDeletes;

    protected $fillable = [
        'title', 'slug', 'body_original', 'body', 'toc', 'publish_date',
    ];

    /**
     * 格式化发布日期
     *
     * @param  string $value
     * @return string
     */
    public function getPublishDateAttribute($value)
    {
        return date('Y-m-d', strtotime($value));
    }

    /**
     * 全文搜索字段
     *
     * @return array
     */
    public function toSearchableArray()
    {
        return [
            'title'        => $this->title,
            'body'         => $this->body_original,
            'publish_date' => $this->publish_date,
            'tags'         => $this->tags->pluck('name'),
        ];
    }

    /**
     * 获取文章摘要
     *
     * @return string
     */
    public function getSummaryAttribute()
    {
        return strstr($this->body, '<!--more-->', true) ?: $this->body;
    }

    /**
     * 按最新排序
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeNewest($query)
    {
        return $query->orderBy('publish_date', 'desc')
                    ->orderBy('created_at', 'desc');
    }

    /**
     * 按年月分组
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeGroupByYears($query)
    {
        return $query->selectRaw('YEAR(publish_date) as publish_year, MONTH(publish_date) as publish_month, count(id) as quantity')
                    ->groupBy('publish_year')
                    ->groupBy('publish_month')
                    ->orderBy('publish_year', 'desc')
                    ->orderBy('publish_month', 'desc');
    }

    /**
     * 查询指定年月数据
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @param  string $years
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeIsYears($query, $years)
    {
        if (empty($years)) {
            return $query;
        }

        $end_years = date('Y-m', strtotime('first day of +1 month', strtotime($years)));

        return $query->where('publish_date', '>=', $years)
                    ->where('publish_date', '<', $end_years);
    }

    /**
     * 关联标签
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }
}
